﻿using Mobileterminal.Common;
using Mobileterminal.Dtos;
using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Mobileterminal.Forms
{
    public partial class EditapparatusForm : UIEditForm
    {
        private ApparatusDto app; // 使用你的DTO类
        public EditapparatusForm(string apparatusId)
        {
            InitializeComponent();
            MessageBox.Show("编辑");
            /*   var apparatusId = this.uiDataGridView1.Rows[e.RowIndex].Cells["apparatusId"].Value.ToString();
               var pdata = new { ApparatusId = apparatusId };
               HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(pdata), Encoding.UTF8, "application/json");
               var json = await HttpClientHelper.ClientAsync("get", "https://localhost:7224/api/Apparatus/QueryApparatusById", true, httpContent);*/

            /*     var url = $"https://localhost:7224/api/Apparatus/GetById?apparatusId={apparatusId}";
                 var json =  HttpClientHelper.ClientAsync("GET", url);
                 var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Result<List<ApparatusDto>>>(json);*/



            // 初始化时异步加载数据
            this.Load += async (sender, e) => await LoadDataAsync(apparatusId);
        }



        //反填
        private async Task LoadDataAsync(string apparatusId)
        {
            var url = $"https://localhost:7224/api/Apparatus/QueryApparatusById?ApparatusId={apparatusId}";
            var json = HttpClientHelper.ClientAsync("GET", url);
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Result<List<ApparatusDto>>>(await json);
            if (result != null && result.Data != null && result.Data.Count > 0)
            { 
                 app=result.Data[0];
                uiComboBox1.Text = app.ApparatusTypeName;
                uiTextBox6.Text = app.ApparatusNo;
                uiTextBox3.Text = app.ApparatusName;
                uiTextBox1.Text = app.ApparatusModel;
                uiTextBox2.Text = app.ApparatusNnit;
                uiTextBox5.Text = app.ApparatusPrice;
                // 初始化分类下拉框（需要提前加载分类数据）
                LoadApparatusTypes(app.ApparatusTypeId);
                // 绑定耐用属性（假设1=耐用品，2=一次性）
                uiRadioButton1.Checked = app.Durableproperties == 1;
                uiRadioButton2.Checked = app.Durableproperties == 2;


            }
        }

        public static List<AppsTypes> appsTypes = new List<AppsTypes>();
        /// <summary>
        /// 加载分类数据
        /// </summary>
        /// <param name="apparatusTypeId"></param>
        /// <exception cref="NotImplementedException"></exception>
        private async void LoadApparatusTypes(int apparatusTypeId)
        {

            //获取分类对应的分类名称--下拉框
        
                var url = "https://localhost:7224/api/ApparatusType/QueryApparatusType";


                var json = await HttpClientHelper.ClientAsync("GET", url);
                var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Result<List<AppsTypes>>>(json);
                if (result.Code == 200)
                {
                    uiComboBox1.DataSource = result.Data;
                    uiComboBox1.DisplayMember = "ApparatusTypeName";
                    uiComboBox1.ValueMember = "ApparatusTypeId";
                uiComboBox1.SelectedValue = apparatusTypeId; 
            }
            
        }

        private void uiLabel6_Click(object sender, EventArgs e)
        {

        }

        private void EditapparatusForm_Load(object sender, EventArgs e)
        {

        }

        private void uiLabel3_Click(object sender, EventArgs e)
        {

        }

        private void uiRadioButton2_CheckedChanged(object sender, EventArgs e)
        {
            if (uiRadioButton2.Checked)
            {
                uiRadioButton1.Checked = false;
            }
        }

        private void uiLabel2_Click(object sender, EventArgs e)
        {

        }

        private void uiTextBox6_TextChanged(object sender, EventArgs e)
        {

        }

        private void uiLabel8_Click(object sender, EventArgs e)
        {

        }

        private void uiTextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void uiTextBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void uiTextBox5_TextChanged(object sender, EventArgs e)
        {

        }

        private void uiTextBox3_TextChanged(object sender, EventArgs e)
        {

        }

        private void uiLabel1_Click(object sender, EventArgs e)
        {

        }

        private void uiLabel4_Click(object sender, EventArgs e)
        {

        }

        private void uiLabel5_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 修改确定按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                // 更新数据模型
                app.ApparatusNo = uiTextBox6.Text;
                app.ApparatusName = uiTextBox3.Text;
                app.ApparatusModel = uiTextBox1.Text;
                app.ApparatusNnit = uiTextBox2.Text;
                app.ApparatusPrice = uiTextBox5.Text;
                app.ApparatusTypeId = (int)uiComboBox1.SelectedValue;
                app.Durableproperties = uiRadioButton1.Checked ? 1 : 2;
             
                // 序列化并创建请求内容
                var json = JsonConvert.SerializeObject(app);
                HttpContent httpContent = new StringContent(json, Encoding.UTF8, "application/json");
                // 发送PUT请求
                var responseJson = await HttpClientHelper.ClientAsync(
                    "PUT",
                    "https://localhost:7286/api/Apparatus/UpdataApparatus",  // 修正URL拼写
                    true,
                    httpContent
                );

                if (string.IsNullOrEmpty(responseJson))
                {
                    MessageBox.Show("服务器返回空响应，请检查服务端状态或请求数据。");
                    return;
                }

                // 反序列化响应
                var result = JsonConvert.DeserializeObject<ApparaData>(responseJson);
                if (result != null)
                {
                    MessageBox.Show("修改成功");
                }
                else
                {
                    MessageBox.Show("反序列化失败，响应内容格式不正确。");
                }
            }
            catch (HttpRequestException ex)
            {
                MessageBox.Show($"网络请求失败：{ex.Message}");
            }
            catch (JsonException ex)
            {
                MessageBox.Show($"解析响应失败：{ex.Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误：{ex.Message}");
            }



        }

        private void btnCancel_Click(object sender, EventArgs e)
        {

        }

        private void uiRadioButton1_CheckedChanged(object sender, EventArgs e)
        {
            if (uiRadioButton1.Checked)
            {
                uiRadioButton2.Checked = false;
            }
        }

        private void uiComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}
